import { defineStore } from 'pinia';
import { RouteRecordRawNew, RoteMenuStore } from '../type/index.d';
import { nameEnum } from '../type/namEnum.d';
import { RouteRecordRaw } from 'vue-router';
import { hiddenRoutes, routesList } from '@/router/route';
import { MenuData } from '@/api/types/user';
const Module = import.meta.glob('@/views/**/*.vue');
//懒加载组件
function loadComponent(url: string) {
  const path = Module[`/src/views/${url}`];
  return path;
}
export const useRouteStore = defineStore(nameEnum.ROUTEMENU, {
  /**
   *
   * @returns 全部路由信息 routeList    选中路由  selectedKeys  ，stairMenu 第一层路由
   */
  state: (): RoteMenuStore<RouteRecordRawNew, MenuData> => {
    return {
      routeList: [],
      selectedKeys: [],
      defaultMenuItem: {} as RouteRecordRawNew,
      btnAuth: [],
    };
  },
  getters: {
    getRouteList(): any {
      return this.defaultMenuItem;
    },
    getSelectValue(): any {
      return this.selectedKeys;
    },
  },
  actions: {
    /**
     *
     * @param routers 需要动态注册的路由配置
     * @returns   返回动态注册路由
     */
    // 递归添加组件
    dynamicRouter(routers: RouteRecordRawNew[]): RouteRecordRawNew[] {
      const list: RouteRecordRawNew[] = [];
      routers.forEach((itemRouter, index) => {
        // 从本地找组件
        list.push({
          ...itemRouter,
          component: loadComponent(itemRouter.component), //没找到则用默认框架组件
        });
        // 是否存在子集
        if (itemRouter.children && itemRouter.children.length) {
          list[index].children = this.dynamicRouter(itemRouter.children);
        }
      });
      return list;
    },
    // 添加到Route
    setRouteList(val: MenuData[], router: any) {
      const list: RouteRecordRawNew[] = [];
      const route = {
        path: '/system',
        name: '菜单',
        component: 'MenuLayout/index.vue',
        meta: {
          transition: 'slide-right',
          menuName: '菜单',
          code: 'MenuLayout',
        },
        // 重定向到第一个路由
        redirect: this.filterRoute((val as MenuData[]) || [], routesList, '/system')[0]?.path || '',
        children: this.filterRoute((val as MenuData[]) || [], routesList, '/system') || [],
      };
      list.push(route);
      //  初始化一级路由信息
      this.defaultMenuItem =
        router?.options?.history?.state.current != '/'
          ? list.filter((item) => router?.options?.history?.state?.current.match(/\/([^\/]+)/g)[0] == item.path)[0]
          : list[0];
      //   注册路由
      this.routeList = this.dynamicRouter(list);

      this.routeList.forEach((m) => {
        router.addRoute(m as RouteRecordRaw);
      });
    },

    /**
     * 匹配路由
     * @param val 后端返回的第二层
     * @param routesList 配置的路由
     * @param path /拼接的地址
     * @returns   返回匹配后的数据
     */
    filterRoute(val: MenuData[], routesList: RouteRecordRawNew[], path?: string): RouteRecordRawNew[] {
      const list: RouteRecordRawNew[] = [];
      val.forEach((d: MenuData, i) => {
        // 过滤自己配置的路由菜单
        const item = routesList?.filter((m) => d.code == m.name)[0];
        // 添加路由信息
        list.push({
          ...d,
          ...item,
          path: `${path}${item?.path ?? ''}`,
          meta: {
            ...item?.meta,
            menuName: d.name || item.meta.menuName,
            icon: d.menuIconUrl || item?.meta?.icon,
          },
          children: null,
        });
        // 如果有子级
        if (d?.children?.length) {
          const childrenList = this.filterRoute(d.children, routesList, `${list[i].path}`);

          list[i].children = childrenList.length > 0 ? childrenList : null;
        }
      });
      hiddenRoutes.forEach((hRoute) => {
        list.push({ ...hRoute, path: `${path}${hRoute?.path ?? ''}` });
      });
      return list;
    },

    // 子路由设置默认值
    setSelectValue(val: string) {
      this.selectedKeys[0] = val;
    },
  },
});
